import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.text.*;
import java.awt.Toolkit;
import javax.swing.*;
import java.util.regex.*;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;


public class CragerGui extends Applet implements ItemListener,ActionListener{

Pattern patternNumbersOnly =Pattern.compile("[0-9]");
Pattern patternAnyThing=Pattern.compile("[0-9]{0,10}");
private boolean removeRegexRestriction=false;
private Matcher match;	

Cities cities = new Cities();


JLabel search=new JLabel("Search For");
JTextField searchTextField=new JTextField(40);

ButtonGroup radioGroup = new ButtonGroup();
JRadioButton salesRadio=new JRadioButton("sales",true);
JRadioButton servicesRadio=new JRadioButton("services");
JRadioButton gigsRadio=new JRadioButton("gigs");

JLabel category=new JLabel("category");


JTextField numberField=new JTextField(10);
JLabel number=new JLabel("Mobile #");
JLabel numberExample= new JLabel("e.g 2345699412");


JComboBox carrierChoice=new JComboBox(cities.getCariers());
JLabel carrier =new JLabel("Mobile Carrier");

JLabel state = new JLabel("State");
JComboBox stateChoice= new JComboBox(cities.getStates());

JLabel city = new JLabel("City");
JComboBox cityChoice=new JComboBox();

String appletCities[][]=cities.getAppletCities();
String urlCities[][]=cities.getUrlCities();
String urlForSaleSections[]=cities.getURLForSaleSections();
String urlServicesSections[]=cities.getUrlServicesSections();
String urlGigsSections[]=cities.getUrlGigsSection();
String carrierEmail[]=cities.getCarrierEmail();
JLabel section=new JLabel("section");
JComboBox categoryChoice= new JComboBox(cities.getForSaleSections());

JButton submit= new JButton("submit");
JLabel numberError = new JLabel("ERROR--MISSING MOBILE #");
JLabel carrierError=new JLabel("ERROR--MISSING CARIER");
JLabel stateError=new JLabel("ERROR---MISSING STATE");
public void init(){

	setBackground(Color.white);
	setSize(500,500);
	setLayout(null);
	search.setBounds(10,30,70,30);
	searchTextField.setBounds(110, 30, 270, 25);
	
	radioGroup.add(salesRadio);
	radioGroup.add(servicesRadio);
	radioGroup.add(gigsRadio);
	category.setBounds(10, 75, 70, 25);
	salesRadio.setBounds(110, 75,70, 25);
	servicesRadio.setBounds(200, 75, 90, 25);
	gigsRadio.setBounds(310, 75, 70, 25);
	
	section.setBounds(10, 135, 70, 25);
	categoryChoice.setBounds(110, 135,170,25);
	
	stateError.setBounds(110, 175, 190, 25);
	state.setBounds(10, 195,70,30);
    stateChoice.setBounds(110, 195, 170, 25);
    
    
    
	city.setBounds(10, 255,90, 25);
	cityChoice.setBounds(110, 255, 170, 25);
	//carrierBox.setBackground(Color.WHITE);
	
	numberError.setBounds(110, 295, 190, 25);
	number.setBounds(10, 315, 70, 25);
	numberField.setBounds(110, 315, 170, 25);
    numberExample.setBounds(290, 315, 170, 25);
    DocumentFilter filter=new DocFilter();
	((AbstractDocument)numberField.getDocument()).setDocumentFilter(filter);
	
    
    carrierError.setBounds(110, 355, 170, 25);
	carrier.setBounds(10, 375, 70, 25);
	carrierChoice.setBounds(110, 375, 170, 25);
	
	submit.setBounds(140, 435, 90, 30);
	numberError.setForeground(Color.red);
	carrierError.setForeground(Color.red);
	stateError.setForeground(Color.red);
	add(search);
	add(searchTextField);
	add(category);
	add(salesRadio);
	add(servicesRadio);
	add(gigsRadio);
	add(categoryChoice);
	add(section);
	add(number);
	add(numberField);
	add(numberExample);
	add(carrier);
	add(carrierChoice);
	add(state);
	add(stateChoice);
	add(city);
	add(cityChoice);
	add(submit);
	stateChoice.addItemListener(this);
	salesRadio.addItemListener(this);
	servicesRadio.addItemListener(this);
	gigsRadio.addItemListener(this);
	submit.addActionListener(this);
	
	
}


public void itemStateChanged(ItemEvent e) {
	 
	String temp[];
	if(e.getSource().equals(stateChoice)){
		cityChoice.removeAllItems();
		temp=appletCities[stateChoice.getSelectedIndex()];
		for (int i=0;i<temp.length;++i){
			cityChoice.addItem(new String(temp[i]));
		}
	}
	else if(e.getSource().equals(salesRadio)){
		categoryChoice.removeAllItems();
		temp=cities.getForSaleSections();
		for (int i=0;i<temp.length;++i){
			categoryChoice.addItem(new String(temp[i]));
		}
	}
	else if(e.getSource().equals(servicesRadio)){
		categoryChoice.removeAllItems();
		temp=cities.getServiceSections();
		for (int i=0;i<temp.length;++i){
			categoryChoice.addItem(new String(temp[i]));
		}
		
	}
	else if(e.getSource().equals(gigsRadio)){
		categoryChoice.removeAllItems();
		temp=cities.getGigsSections();
		for (int i=0;i<temp.length;++i){
			categoryChoice.addItem(new String(temp[i]));
		}
	}
	
}

public void actionPerformed(ActionEvent event){
//it is not necessary to check the source of the action listener and only one the button has an action listener.
	
	if(errorCheck()){
		String temp[];
		String section=null;
        String city=null;
        String email=null;
        String url=null;
        String phoneNumber=null;
		String searchFor=searchTextField.getText();
             searchFor=searchFor.trim();
             searchFor=searchFor.replaceAll(" ", "+");
      
      if(radioGroup.getSelection().equals(salesRadio.getModel())){
    	 section=urlForSaleSections[categoryChoice.getSelectedIndex()];
      }
      else if(radioGroup.getSelection().equals(servicesRadio.getModel())){
    	  section=urlServicesSections[categoryChoice.getSelectedIndex()];
      }
      else if(radioGroup.getSelection().equals(gigsRadio.getModel())){
    	  section=urlGigsSections[categoryChoice.getSelectedIndex()];
      }
      temp=urlCities[stateChoice.getSelectedIndex()];//first load cities for the state
      city=temp[cityChoice.getSelectedIndex()];//load city.
      
      phoneNumber=numberField.getText();
      email=phoneNumber+carrierEmail[carrierChoice.getSelectedIndex()];
      
      //http://gainesville.craigslist.org/search/sss?query=monitor&srchType=A
      if(searchFor.length()==0)url="http://"+city+".craigslist.org/search/"+section+"?query=+";
      else url="http://"+city+".craigslist.org/search/"+section+"?query="+searchFor+"&srchType=A";
      
      
      searchTextField.setText("");
      removeRegexRestriction=true; //this helps to clear the numberField
      numberField.setText("");
      radioGroup.setSelected(salesRadio.getModel(), true);
      
      temp=cities.getForSaleSections();
      categoryChoice.removeAllItems(); //remove all items in sections then relaod with for loop below
		for (int i=0;i<temp.length;++i){
			categoryChoice.addItem(new String(temp[i]));
		}
		stateChoice.setSelectedIndex(0);
		carrierChoice.setSelectedIndex(0);
		
		System.out.print(url+"\n"+phoneNumber+"\n"+email);
      }
	
}



public boolean errorCheck(){ //return true is there are no errors
	boolean value=true;
	remove(stateError);
	remove(carrierError);
	remove(numberError);

	if(stateChoice.getSelectedIndex()==0)
		{
		value=false;
		add(stateError);
		}
    if(numberField.getText().length()!=10){
    	value=false;
    	add(numberError);
    }
    if(carrierChoice.getSelectedIndex()==0){
    	value=false;
    	add(carrierError);
    }
    repaint();
    return value;
}
	class DocFilter extends DocumentFilter {
	
        public void replace(FilterBypass fb, int offset, int length,String text, AttributeSet attrs){
        	if(removeRegexRestriction){
        		match=patternAnyThing.matcher(text);
        		removeRegexRestriction=false;
        	}
        	else match=patternNumbersOnly.matcher(text);
            try{
        	if(match.find()&&(fb.getDocument().getLength()+text.length()<=10))fb.replace(offset, length, text, attrs);
        	else Toolkit.getDefaultToolkit().beep();
            }
            catch(BadLocationException e){
            	
            }
            

        }
    }

	
}
